<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" class="compact-form">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="订单名称" :labelCol="{span: 6}" :wrapperCol="{span: 18}">
              <a-input v-decorator="['orderName']" placeholder="订单名称" disabled />
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item label="程序员" :labelCol="{span: 6}" :wrapperCol="{span: 18}">
              <a-input v-decorator="['programmerName']" placeholder="程序员" disabled />
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item label="结算金额" :labelCol="{span: 6}" :wrapperCol="{span: 18}">
              <a-input-number
                v-decorator="['billAmount', {rules: [{required: true, message: '请输入结算金额!'}]}]"
                :min="0"
                :precision="2"
                style="width: 100%"
                placeholder="请输入结算金额" />
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item label="结算类型" :labelCol="{span: 6}" :wrapperCol="{span: 18}">
              <j-dict-select-tag
                v-decorator="['billType', {rules: [{required: true, message: '请选择结算类型!'}]}]"
                placeholder="请选择结算类型"
                dictCode="bill_type" />
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item label="支付方式" :labelCol="{span: 6}" :wrapperCol="{span: 18}">
              <j-dict-select-tag
                v-decorator="['paymentMethod', {rules: [{required: true, message: '请选择支付方式!'}]}]"
                placeholder="请选择支付方式"
                dictCode="payment_method" />
            </a-form-item>
          </a-col>
          
          <a-col :span="12">
            <a-form-item label="结算日期" :labelCol="{span: 6}" :wrapperCol="{span: 18}">
              <j-date
                v-decorator="['billDate', {rules: [{required: true, message: '请选择结算日期!'}]}]"
                :showTime="false"
                dateFormat="YYYY-MM-DD"
                placeholder="请选择结算日期" />
            </a-form-item>
          </a-col>
          
          <a-col :span="24">
            <a-form-item label="备注" :labelCol="{span: 3}" :wrapperCol="{span: 21}">
              <a-textarea
                v-decorator="['remarks']"
                placeholder="请输入备注信息"
                :rows="4" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </j-modal>
</template>

<script>
  import { httpAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import moment from 'moment'
  import JDate from '@/components/jeecg/JDate'
  import JDictSelectTag from '@/components/dict/JDictSelectTag'
  
  export default {
    name: "BProgrammerBillModal",
    components: {
      JDate,
      JDictSelectTag
    },
    data () {
      return {
        title: "添加结算记录",
        width: 800,
        visible: false,
        model: {},
        labelCol: { span: 4 },
        wrapperCol: { span: 20 },
        confirmLoading: false,
        form: this.$form.createForm(this),
        url: {
          add: "/order/bProgrammerBillInfo/add",
          edit: "/order/bProgrammerBillInfo/edit"
        }
      }
    },
    methods: {
      // 初始化表单
      initForm() {
        this.form.resetFields();
        this.model = {};
        this.confirmLoading = false;
      },
      
      // 显示模态框
      show(orderInfo, record) {
        this.initForm();
        this.visible = true;
        
        if (record && record.id) {
          // 编辑模式
          this.title = "编辑结算记录";
          this.model = Object.assign({}, record);
          // 保存订单信息
          this.model.orderId = record.orderId;
          this.model.programmerId = record.programmerId;
          
          // 设置表单值
          this.$nextTick(() => {
            let formValues = pick(record, ['billAmount', 'billType', 'paymentMethod', 'remarks']);
            
            // 处理日期
            if (record.billDate) {
              formValues.billDate = moment(record.billDate, 'YYYY-MM-DD');
            }
            
            this.form.setFieldsValue({
              ...formValues,
              orderName: orderInfo.orderName,
              programmerName: orderInfo.programmerName
            });
          });
        } else {
          // 添加模式
          this.title = "添加结算记录";
          this.model = Object.assign({}, orderInfo);
          
          // 设置默认值
          this.$nextTick(() => {
            this.form.setFieldsValue({
              orderName: this.model.orderName,
              programmerName: this.model.programmerName,
              billDate: moment()
            });
          });
        }
      },
      
      // 确定按钮点击
      handleOk() {
        const that = this;
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            
            // 处理日期格式
            if (values.billDate) {
              // 确保billDate是moment对象，然后转换为字符串
              if (moment.isMoment(values.billDate)) {
                values.billDate = values.billDate.format('YYYY-MM-DD');
              } else if (typeof values.billDate === 'object' && values.billDate.toString) {
                // 如果是Date对象或其他对象，尝试转换
                values.billDate = moment(values.billDate).format('YYYY-MM-DD');
              } else if (typeof values.billDate === 'string' && values.billDate.indexOf('-') > 0) {
                // 已经是字符串格式，不需要处理
              } else if (typeof values.billDate === 'number' || /^\d+$/.test(values.billDate)) {
                // 如果是时间戳，转换为字符串
                values.billDate = moment(parseInt(values.billDate)).format('YYYY-MM-DD');
              }
              
              console.log('处理后的日期:', values.billDate);
            }
            
            // 添加订单ID和程序员ID
            if (this.title === "编辑结算记录") {
              // 编辑模式，使用记录中的ID
              values.orderId = this.model.orderId;
              values.programmerId = this.model.programmerId;
              values.id = this.model.id;
            } else {
              // 添加模式，使用订单信息中的ID
              values.orderId = this.model.id;
              values.programmerId = this.model.programmerId;
            }
            
            console.log('表单提交数据', values);
            
            // 发送请求
            let httpUrl = this.url.add;
            let method = 'post';
            
            if (this.title === "编辑结算记录") {
              httpUrl = this.url.edit;
              method = 'put';
            }
            
            httpAction(httpUrl, values, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message || '保存成功');
                that.$emit('ok');
                that.visible = false;
              } else {
                that.$message.warning(res.message || '保存失败');
              }
            }).finally(() => {
              that.confirmLoading = false;
            });
          }
        });
      },
      
      // 取消按钮点击
      handleCancel() {
        this.visible = false;
      }
    }
  }
</script>

<style scoped>
  /* 紧凑型表单样式 */
  .compact-form /deep/ .ant-form-item {
    margin-bottom: 12px;
  }
  
  .compact-form /deep/ .ant-form-item-label {
    line-height: 32px;
  }
  
  .compact-form /deep/ .ant-form-item-control {
    line-height: 32px;
  }
</style> 